<template>
  <div class="menu">
    <el-menu :default-active="activeIndex" class="el-menu-vertical-demo" @select="handleSelect">
      <template v-for="item in menuItems" :key="item.name">
        <el-menu-item v-if="item.meta.leaf" :index="item.name">
          <i :class="item.icon"></i>
          <span>{{ item.meta.title }}</span>
        </el-menu-item>
        <el-sub-menu v-else :index="item.name">
          <template #title>
            <i :class="item.icon"></i>
            <span>{{ item.meta.title }}</span>
          </template>
          <el-menu-item v-for="child in item.children" :key="child.name" :index="child.name">
            <i :class="child.icon"></i>
            <span>{{ child.meta.title }}</span>
          </el-menu-item>
        </el-sub-menu>
      </template>
    </el-menu>
  </div>
</template>

<script>
import { computed, ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMenu, ElSubMenu, ElMenuItem, ElMessage } from 'element-plus';
import service from "@/utils/request";

export default {
  name: 'NavMenu',
  components: {
    ElMenu,
    ElSubMenu,
    ElMenuItem
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const activeIndex = ref('');
    const menuData = ref([]); // 确保初始值是数组
    //const userRole = localStorage.getItem('employeeDepartment') || ''; // 获取用户角色，默认为空字符串

    // 从后端获取菜单数据
    const fetchMenuData = async () => {
      try {
        const response = await service.get('admin/employee/menu');
        if (Array.isArray(response.data.data)) {
          menuData.value = response.data.data;
        } else {
          console.error('Invalid menu data format:', response.data.data);
          menuData.value = [];
        }
      } catch (error) {
        console.error('Failed to fetch menu data:', error);
        menuData.value = [];
      }
    };

    // 构建菜单树并匹配路由
    const buildMenuTree = (menuData, parentId = 0, routes) => {
      console.log('Building menu tree with data:', menuData); // 调试日志

      return (menuData || []).filter(item => item.parentId === parentId).map(item => {
        const route = routes.find(r => r.name === item.name);

        const menuItem = {
          ...item,
          meta: {
            ...item.meta,
            title: item.title,
            icon: item.icon,
            hidden: item.hidden,
            // roles: [userRole] // 用户角色
          },
          children: buildMenuTree(menuData, item.id, routes)
        };

        if (route) {
          Object.assign(menuItem, route.meta); // 将路由元信息附加到菜单项
          menuItem.path = route.path;
          menuItem.component = route.component;
        }
          // 如果 hidden 为 1，则过滤掉该菜单项
          if (menuItem.meta.hidden === 1) {
              return null;
          }
        if (!menuItem.children || menuItem.children.length === 0) {
          delete menuItem.children;
          menuItem.meta.leaf = true;
        }

        return menuItem;
      }).filter(Boolean); // 移除未找到对应路由的菜单项
    };

    // 计算属性：动态生成菜单项
    const menuItems = computed(() => {
      const allRoutes = router.getRoutes();
      console.log('All available routes:', allRoutes); // 调试日志
      return buildMenuTree(menuData.value, 0, allRoutes);
    });

    // 处理菜单项选择事件
    const handleSelect = (index) => {
      const route = allRoutes.value.find(r => r.name === index);

      if (route) {

          router.push({ name: index });
          activeIndex.value = index;

      } else {
        ElMessage.error('路由不存在');
      }
    };

    // 初始化时获取菜单数据
    onMounted(() => {
      fetchMenuData();
      activeIndex.value = route.name; // 设置默认激活的菜单项
    });

    // 定义所有路由的计算属性，以避免每次调用buildMenuTree都重新获取路由
    const allRoutes = computed(() => router.getRoutes());

    return {
      menuItems,
      activeIndex,
      handleSelect
    };
  }
};
</script>

<style scoped>
/* 菜单样式 */
.el-menu-vertical-demo {
  background-color: #ffffff; /* 菜单背景色 */
  border: none;
  margin: auto;
}

.el-menu-item.is-active,
.el-sub-menu.is-active .el-sub-menu__title {
  color: #ffffff; /* 激活字体颜色 */
  background-color: #0849a3; /* 激活背景色 */
}

/* 子菜单样式 */
.el-sub-menu .el-menu {
  background-color: #ffffff; /* 子菜单背景色 */
}

/* 子菜单项悬停样式 */
.el-sub-menu .el-menu-item:hover {
  background-color: #0849a3; /* 子菜单项悬停背景色 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-menu-vertical-demo {
    width: 100%;
  }
}
</style>